const int nLecturas=10; 
int lecturas[nLecturas]; 
int indice = 0;         
int total = 0;          
int media = 0;          
unsigned long tiempo = 0;                    
unsigned long distancia = 0;  
                  
void setup() {
  pinMode(9, OUTPUT); 
  pinMode(2, INPUT);  
  pinMode(3, OUTPUT); 
  for (int i = 0; i < nLecturas; i++) {lecturas[nLecturas] = 0;}
  Serial.begin(9600);
} 

void loop() {
  digitalWrite(3, LOW);
  delayMicroseconds(5);
  digitalWrite(3, HIGH); 
  delayMicroseconds(10); 
  digitalWrite(3, LOW);  
  tiempo = pulseIn(2, HIGH); 
  distancia = 0.017*tiempo;   
  total= total - lecturas[indice];  
  lecturas[indice] = distancia; 
  total= total + lecturas[indice];  
  indice = indice + 1; 
  if (indice >= nLecturas)  {  índice = 0;  }
  media = total / nLecturas;  
  if (media < 255) {
     analogWrite(9, 255 - media);    
  }
  delay(100); 
}

